<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
      <el-table :data="userList" style="width: 100%" stripe border>
        <!-- 展开行 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item,i) of scope.row.children"
              :key="item.id"
              :class="['border-bottom',i===0?'border-top':'','fcenter']"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removePower(scope.row,item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级及三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(items,index) of item.children"
                  :key="items.id"
                  :class="index===0?'':'border-top'"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removePower(scope.row,items.id)"
                    >{{items.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="items2 of items.children"
                      :key="items2.id"
                      type="warning"
                      closable
                      @close="removePower(scope.row,items2.id)"
                    >{{items2.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="changeUser(scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="removeUser(scope.row)"
            >删除</el-button>
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="setRights(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="resetForm">
      <span>
        <el-form :model="addRuleForm" :rules="addRules" ref="addRuleForm">
          <el-form-item label="角色名称" prop="roleName" label-width="80px">
            <el-input v-model="addRuleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc" label-width="80px">
            <el-input v-model="addRuleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="changeDialogVisible"
      width="50%"
      @close="resetChangeForm"
    >
      <span>
        <el-form :model="changeRuleForm" :rules="addRules" ref="changeRuleForm">
          <el-form-item label="角色名称" prop="roleName" label-width="80px">
            <el-input v-model="changeRuleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc" label-width="80px">
            <el-input v-model="changeRuleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetChangeForm">取 消</el-button>
        <el-button type="primary" @click="changeUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->

    <el-dialog title="分配权限" :visible.sync="rightsDialogVisible" width="50%">
      <el-tree
        :data="rightsTreeData"
        :props="defaultProps"
        ref="tree"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defaultCheckedKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRightsBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "roles",
  data() {
    return {
      userList: [], //角色列表数据
      addDialogVisible: false, //控制添加角色对话框
      addRuleForm: {
        //添加角色表单数据
        roleName: "",
        roleDesc: ""
      },
      addRules: {
        //添加角色校验规则
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" }
        ]
      },
      changeDialogVisible: false, //控制修改角色对话框
      changeRuleForm: {
        //修改角色表单数据
        roleName: "",
        roleDesc: ""
      },
      rightsDialogVisible: false, //控制分配权限对话框
      rightsTreeData: [], //树形权限数据
      defaultProps: {
        //树形展示数据方式
        children: "children",
        label: "authName"
      },
      defaultCheckedKeys: [], //分配权限默认选中数据
      defaultId: "" //当前即将分配权限的id
    };
  },
  methods: {
    async getUserList() {
      //请求角色列表数据
      const { data: res } = await this.$axios.get("roles");
      if (res.meta.status === 200) {
        this.userList = res.data;
      } else {
        this.$message.error(res.meta.msg);
      }
    },
    async removePower(user, rightId) {
      //删除权限
      const confirm = await this.$confirm(
        "此操作将永久删除该权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirm === "confirm") {
        const { data: res } = await this.$axios.delete(
          `roles/${user.id}/rights/${rightId}`
        );
        if (res.meta.status === 200) {
          this.$message.success("删除成功");
          user.children = res.data;
        } else {
          this.$message.error(res.meta.msg);
        }
      } else {
        this.$message.error("取消删除");
      }
    },
    addUsers() {
      //添加用户
      this.$refs.addRuleForm.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$axios.post("roles", this.addRuleForm);
        if (res.meta.status === 201) {
          this.$message.success("添加成功");
          this.addDialogVisible = false;
          this.getUserList();
        } else {
          this.$message.success("添加失败");
        }
      });
    },
    resetForm() {
      //重置添加用户表单
      this.$refs.addRuleForm.resetFields();
      this.addDialogVisible = false;
    },
    changeUser(user) {
      //点击按钮弹出修改用户对话框，user传递到对话框中
      this.changeDialogVisible = true;
      this.changeRuleForm = user;
    },
    resetChangeForm() {
      //重置修改用户表单
      this.$refs.changeRuleForm.resetFields();
      this.changeDialogVisible = false;
    },
    changeUserInfo() {
      this.$refs.changeRuleForm.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$axios.post(
          "roles",
          this.changeRuleForm
        );
        if (res.meta.status === 201) {
          this.$message.success("修改成功");
          this.changeDialogVisible = false;
          this.getUserList();
        } else {
          this.$message.success("修改失败");
        }
      });
    },
    async removeUser(user) {
      //删除用户
      const confirm = await this.$confirm(
        "此操作将删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirm === "confirm") {
        const { data: res } = await this.$axios.delete(`roles/${user.id}`);
        if (res.meta.status === 200) {
          this.$message.success("成功删除");
          this.getUserList();
        }
      } else {
        this.$message.error("已取消删除");
      }
    },
    async setRights(row) {
      //分配权限
      this.defaultId = row.id;
      this.rightsDialogVisible = true;
      const { data: res } = await this.$axios.get("rights/tree");
      this.rightsTreeData = res.data;
      const keys = []; // 专门存放所有三级节点的Id
      this.getLeafIds(row, keys);
      this.defaultCheckedKeys = keys;
    },
    // 根据指定的节点和keys数组，递归获取所有三级节点的Id
    getLeafIds(node, keys) {
      if (!node.children) {
        keys.push(node.id);
      } else {
        node.children.forEach(item => this.getLeafIds(item, keys));
      }
    },
    async setRightsBtn() {
      //分配权限确定
      const arr1 = this.$refs.tree.getCheckedKeys();
      const arr2 = this.$refs.tree.getHalfCheckedKeys();
      const rids = [...arr1, ...arr2].join(",");
      const {
        data: res
      } = await this.$axios.post(`roles/${this.defaultId}/rights`, { rids });
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败！");
      }
      this.$message.success("分配权限成功！");
      this.rightsDialogVisible = false;
      this.getUserList();
    }
  },
  created() {
    this.getUserList();
  }
};
</script>

<style scoped>
.el-table {
  margin-top: 30px;
  font-size: 12px;
}
.el-card {
  margin-top: 30px;
}
.el-tag {
  margin: 7px;
}
.border-top {
  border-top: 1px solid rgb(238, 238, 238);
}
.border-bottom {
  border-bottom: 1px solid rgb(238, 238, 238);
}
.fcenter {
  display: flex;
  align-items: center;
}
</style>